package com.six.library.utils

import io.jsonwebtoken.Claims
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import java.util.*
import javax.servlet.http.HttpServletRequest

object JWTUtils {
    //常量
    //定义token返回头部key名称
    const val AUTH_HEADER_KEY = "admin_eastos"

    //过期时间为10天
    const val EXPIRE = (1000 * 60 * 60 * 24 * 10).toLong()

    /**
     * 根据用户名，创建jwtToken
     * @param username
     * @return
     */
    fun createJwtToken(username: String): String {
        val jwtBuilder = Jwts.builder()
        return jwtBuilder //======header====
            .setHeaderParam("typ", "JWT")
            .setHeaderParam("alg", "HS256") //======payload===
            .setSubject("user-login")
            .setId(UUID.randomUUID().toString()) //过期时间
            .setExpiration(Date(System.currentTimeMillis() + EXPIRE)) //自定义数据
            .claim("username", username)
            .claim("islogin", true) //======singnature====
            .signWith(SignatureAlgorithm.HS256, Constant.APP_SECRET) //=====拼接成字符串=====
            .compact()
    }

    /**
     * 根据用户id和用户名，创建token
     * @param userid
     * @param username
     * @return
     */
    fun createJwtToken(userid: String, username: String): String {
        val jwtBuilder = Jwts.builder()
        return jwtBuilder //======header====
            .setHeaderParam("typ", "JWT")
            .setHeaderParam("alg", "HS256") //======payload===
            .setSubject("user-login")
            .setId(UUID.randomUUID().toString()) //过期时间
            .setExpiration(Date(System.currentTimeMillis() + EXPIRE)) //自定义数据
            .claim("userid", userid)
            .claim("username", username)
            .claim("islogin", true) //======singnature====
            .signWith(SignatureAlgorithm.HS256, Constant.APP_SECRET) //=====拼接成字符串=====
            .compact()
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    @JvmStatic
    fun checkToken(token: String?): Boolean {
        if (token == null || token.isEmpty() || "" == token.trim { it <= ' ' }) {
            return false
        }
        try {
            val claimsJws = Jwts.parser().setSigningKey(Constant.APP_SECRET).parseClaimsJws(token)
        } catch (ex: Exception) {
            return false
        }
        return true
    }



    /**
     * 校验token
     * @param request
     * @return
     */
    fun checkToken(request: HttpServletRequest): Boolean {
        val token = request.getHeader(AUTH_HEADER_KEY)
        if (token == null || token.isEmpty() || "" == token.trim { it <= ' ' }) {
            return false
        }
        try {
            val claimsJws = Jwts.parser().setSigningKey(Constant.APP_SECRET).parseClaimsJws(token)
        } catch (ex: Exception) {
            return false
        }
        return true
    }

    /**
     * 获得token数据
     * @param token
     * @return
     */
    fun parseToken(token: String): Claims {
        val jwtParser = Jwts.parser()
        val claimsJws =
            jwtParser.setSigningKey(Constant.APP_SECRET).parseClaimsJws(token)
        //获得数据
        return claimsJws.body
    }

    /**
     * 获得token数据
     * @param token
     * @return
     */
    fun getTokenUserName(token: String): String {
        val jwtParser = Jwts.parser()
        val claimsJws = jwtParser.setSigningKey(Constant.APP_SECRET).parseClaimsJws(token)
        //获得数据
        val claims = claimsJws.body
        return claims["username"].toString()
    }

    /**
     * 获得token数据
     * @param token
     * @return
     */
    fun getTokenUserId(token: String): String {
        val jwtParser = Jwts.parser()
        val claimsJws = jwtParser.setSigningKey(Constant.APP_SECRET).parseClaimsJws(token)
        //获得数据
        val claims = claimsJws.body
        return claims["userid"].toString()
    }

    /**
     * 获得token数据
     * @param token
     * @return
     */
    fun getTokenData(token: String, datakey: String): String {
        val jwtParser = Jwts.parser()
        val claimsJws = jwtParser.setSigningKey(Constant.APP_SECRET).parseClaimsJws(token)
        //获得数据
        val claims = claimsJws.body
        return claims[datakey].toString()
    }

    @JvmStatic
    fun main(args: Array<String>) {
        //创建token
        val username = "admin"
        val jwtToken = createJwtToken(username)
        println(jwtToken)
        //检证token
        val result = checkToken(jwtToken)
        println(result)
        //获得数据
        println(getTokenUserName(jwtToken))
        println(getTokenData(jwtToken, "islogin"))
    }
}